package com.idea.relax.log.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.lang.annotation.*;
import java.util.Map;
import java.util.Objects;

/**
 * @author salad
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ConditionalOnLoggingType.LogTypeCondition.class)
public @interface ConditionalOnLoggingType {

    /**
     *
     */
    LoggingType value();

    @Slf4j
    class LogTypeCondition extends SpringBootCondition {

        @Override
        public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
            Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnLoggingType.class.getName());
            Object value = Objects.requireNonNull(attributes).get("value");
            LoggingType logType = LoggingType.valueOf(value.toString());
            if (!logType.equals(LoggingTypeSniffer.sniff())) {
                log.warn("The " + logType.name() + " logging framework is not used.");
                return ConditionOutcome.noMatch("The " + logType.name() + " logging framework is not used.");
            }
            return ConditionOutcome.match();
        }
    }

}